package xaj.main;

import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Collection;

import xaj.scc.util.mapping.AddGrammar;
import xaj.scc.visit.Visitor_Giorgio_01;
import xaj.selector.Selector;
import xaj.selector.SelectorImpl;

public class SCCompiler {

	private static final String HEADER = "scc: ";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String sources = ".", output = "bin";
		try {
			for (int i = 0; i < args.length; ++i) {
				if (args[i].equalsIgnoreCase("-sourceroots")) {
					if (i + 1 < args.length)
						sources = args[++i];
					else
						throw new Exception(
								"No source root specified after -sourceroots");
				} else if (args[i].equals("-d")) {
					if (i + 1 < args.length)
						output = args[++i];
					else
						throw new Exception("No output specified after -d");
				} else {
					throw new Exception("Invalid switch: " + args[i]);
				}
			}
		} catch (Exception e) {
			System.err.println(HEADER + e.getMessage());
			usage();
		}
		/**
		 * Separa as classes sinticas que devem ser compiladas
		 */
		Collection<String> s = Loadder.loadSourceRoots(sources);
		Selector selector = new SelectorImpl();
		s = selector.selectSyntaxClass(s);
		
		/**
		 * Configura os parâmetros do executar o compilador do abc com a extensão
		 * syntax class
		 */
		String arg[] = new String[s.size() + 4];
		int i = 0;
		arg[i++] = "-d";
		arg[i++] = "output";
		arg[i++] = "-ext";
		arg[i++] = "xaj.scc";
		for(String filename : s) {
			arg[i++] = filename; 
		}
		
		//Coisa que o Giorgio colocou
		//---------------------------
		Visitor_Giorgio_01.init();
		//----------------------------
		abc.main.Main.main(arg);
		//Coisa do Giorgio
		//------------------------
		Visitor_Giorgio_01.end();
		//-----------------------
		abc.main.Main.resetStatic();
		
		PrintStream saida;
		try {

			saida = new PrintStream(xaj.main.Properties.XAJ_HOME + "/tmp/xaj.ppg");

			System.out.println(AddGrammar.getInstance().toString());
			saida.println(AddGrammar.getInstance().toString());
			saida.close();

		} catch (FileNotFoundException e) {
			System.out.println("error file");
		}		
	}

	public static void usage() {
		/**
		 * @TODO - imprirmir uma mensagem mais adequada
		 */
		System.err.println("Usage: scc [-sourceroots root] [-d output]");
		System.exit(1);
	}
}
